import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['font.size'] = 15
# 创建数据框
data = {
    'Feature': ['Education', 'Gender', 'PerformanceRating', 'RelationshipSatisfaction',
                'BusinessTravel', 'Department', 'EducationField', 'EnvironmentSatisfaction',
                'JobInvolvement', 'JobLevel', 'JobRole', 'JobSatisfaction',
                'ManitalStatus', 'OverTime', 'StockOptionLevel', 'WorkLifeBalance'],
    'P-value': [0.191021, 0.636798, 0.150684, 0.258011, 0.004087, 0.025272,
                0.023961, 0.002108, 0.000011, 0.000000, 0.000000, 0.000438,
                0.000000, 0.000000, 0.000000, 0.034669],
    'Significant': [False, False, False, False, True, True, True, True,
                    True, True, True, True, True, True, True, True]
}

df = pd.DataFrame(data)

# 按p值排序（从低到高）
df = df.sort_values(by='P-value', ascending=True)

# 创建图表
plt.figure(figsize=(14, 10))

# 创建颜色映射：显著特征为深蓝色，不显著为浅灰色
colors = ['#1f77b4' if s else '#d3d3d3' for s in df['Significant']]

# 绘制水平条形图（更好展示特征名称）
bars = plt.barh(df['Feature'], df['P-value'], color=colors, alpha=0.9, edgecolor='black')

# 添加显著性阈值线
plt.axvline(x=0.05, color='red', linestyle='--', linewidth=2, alpha=0.7)
plt.text(0.055, 2, '显著性阈值 (p=0.05)', fontsize=12, color='red', fontweight='bold')

# 添加p值标签
for i, (feature, p, sig) in enumerate(zip(df['Feature'], df['P-value'], df['Significant'])):
    # 格式化p值显示
    if p < 0.0001:
        label = "<0.0001"
    elif p < 0.001:
        label = f"{p:.4f}"[1:]  # 显示0.000X
    else:
        label = f"{p:.4f}"

    # 根据显著性调整标签位置
    x_pos = p + 0.01 if sig else p - 0.05
    ha = 'left' if sig else 'right'
    color = 'black' if sig else 'gray'

    plt.text(x_pos, i, label, ha=ha, va='center', fontsize=10, color=color,
             fontweight='bold' if sig else 'normal')

# 添加星号标记表示显著水平
for i, p in enumerate(df['P-value']):
    if p < 0.05:
        stars = '***' if p < 0.001 else '**' if p < 0.01 else '*'
        plt.text(0.01, i, stars, ha='right', va='center', fontsize=14, color='red')

# 设置标题和标签
plt.title('特征与目标变量的关联显著性 (卡方检验 p值)', fontsize=16, pad=20, fontweight='bold')
plt.xlabel('p值', fontsize=12)
plt.ylabel('特征', fontsize=12)

# 使用对数尺度以便更好地区分小p值
plt.xscale('log')
plt.xlim(1e-7, 2)  # 设置x轴范围
plt.gca().invert_yaxis()  # 反转y轴使最小p值在顶部

# 添加网格线
plt.grid(axis='x', linestyle='--', alpha=0.3)

# 添加图例
from matplotlib.patches import Patch

legend_elements = [
    Patch(facecolor='#1f77b4', label='显著关联 (p<0.05)'),
    Patch(facecolor='#d3d3d3', label='不显著关联 (p≥0.05)'),
    Patch(facecolor='none', edgecolor='red', linestyle='--', label='显著性阈值 (0.05)')
]
plt.legend(handles=legend_elements, loc='lower right', fontsize=12)

# 添加数据来源说明
plt.figtext(0.5, 0.01, "数据来源: 卡方检验结果 | 可视化: Python Matplotlib",
            ha="center", fontsize=10, alpha=0.7)

# 调整布局
plt.tight_layout()

# 保存图表
plt.savefig('feature_significance_analysis.png', dpi=300, bbox_inches='tight')

# 显示图表
plt.show()